<template>
    <div class="container">
        <div class="action-buttons">
            <el-button type="primary" class="createBtn" @click="process" style="margin-left: -5px;">数据预处理</el-button>
            <el-button type="primary" @click="exportData" style="margin-left: 10px;">导出数据</el-button>
            <el-select v-model="exportFormat" placeholder="选择导出格式" style="margin-left: 10px; width: 120px;" v-show="false">
                <el-option label="CSV" value="csv"></el-option>
            </el-select>
        </div>

        <el-table :data="tableData.data" style="width: 100%;margin-top: 20px;">
            <el-table-column v-for="(model, index) in tableDataDetail" :prop="model.field" :label="model.name"
                :key="index">
                <template #default="scope">
                    <!-- 检查该列是否是图片列 -->
                    <div v-if="model.field === 'imgurl'">
                        <img :src="scope.row[model.field]" alt="Image"
                            style="width: 100px; height: 100px; object-fit: cover;" />
                    </div>
                    <div v-else>
                        {{ scope.row[model.field] }}
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            :current-page="currentPage" @current-change="handlePageChange" @size-change="handlePageSizeChange"
            style="margin-top: 10px;" />

        <!-- 创建数据表单 -->
        <div v-if="isCreate" class="writeForm" style="height: 550px;">
            <ul>
                <li>
                    <p>新增数据</p>
                </li>
                <li v-for="(item, index) in CreateDataDetail.data" :key="index">
                    <p>{{ item.name }}</p>
                    <el-input class="elInput" :placeholder="item.name" v-model="item.value" clearable></el-input>
                </li>
                <li>
                    <el-button @click="createRow">取消</el-button>
                    <el-button type="primary" @click="realyCreate">确认</el-button>
                </li>
            </ul>
        </div>

        <!-- 修改数据表单 -->
        <div v-if="isWrite" class="writeForm" style="height: 550px;">
            <ul>
                <li>
                    <p>修改数据</p>
                </li>
                <li v-for="(item, index) in ruleForm.data" :key="index">
                    <p>{{ item.name }}</p>
                    <el-input class="elInput" :placeholder="item.name" v-model="item.value" clearable></el-input>
                </li>
                <li>
                    <el-button @click="writeRow(null)">取消</el-button>
                    <el-button type="primary" @click="realyWrite">确认</el-button>
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { reactive, ref } from 'vue';
    import axios from 'axios';
    import { ElMessage, ElMessageBox, ComponentSize, ElLoading } from 'element-plus';
    import * as XLSX from 'xlsx';
    import type { UploadProps, UploadUserFile } from 'element-plus';
    // import { Loading } from 'element-ui';


    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const exportFormat = ref < 'csv' > ('csv');
    const tableDataDetail = reactive([
        { field: 'id', name: '编号' },
        { field: 'title', name: '片名' },
        { field: 'star', name: '评分' },
        // { field: 'floor', name: '楼层' },
        { field: 'quote', name: '引言' },
        { field: 'number', name: '评价人数' },
        { field: 'year', name: '年份' },
        { field: 'regions', name: '地区' },
        { field: 'director', name: '导演' },
        { field: 'actor', name: '演员' },

    ])

    const tableData = reactive({ data: [] })
    const alltableData = reactive({ data: [] })
    const handlePageChange = (page: number) => {
        currentPage.value = page
        fetchTableData()
    }

    const handlePageSizeChange = (size: number) => {
        pageSize.value = size
        fetchTableData()
    }

    function fetchTableData() {
        axios.get('http://127.0.0.1:5000/get_all_movie', {
            params: {
                page: currentPage.value,
                per_page: pageSize.value
            }
        }).then((res) => {
            tableData.data = res.data.data
            total.value = res.data.total[0]
        }).catch(error => {
            ElMessage.error('加载数据失败')
        })
    }

    function fetchAllData() {
        axios.get('http://127.0.0.1:5000/getAllmovie', {
        }).then((res) => {
            alltableData.data = res.data.data
        }).catch(error => {
            ElMessage.error('加载数据失败')
        })
    }
    // 初始加载数据
    fetchTableData()
    fetchAllData()

    function exportData() {

        const dataToExport = alltableData.data;

        // 根据选择的导出格式调用相应的导出函数
        if (exportFormat.value === 'csv') {
            exportCSV(dataToExport); // 导出为CSV
        } else if (exportFormat.value === 'excel') {
            exportExcel(dataToExport); // 导出为Excel
        }
    }

    // 导出为CSV函数
    function exportCSV(data = alltableData.data) {
        console.log("数据:" + data)
        // 将所有列名作为CSV的头部
        const headers = tableDataDetail.map(item => item.name);
        // 将每一行数据转换为CSV格式
        const rows = data.map(row => tableDataDetail.map(item => row[item.field]).join(','));
        // 组合CSV内容
        const csvContent = [headers.join(','), ...rows].join('\n');
        // 创建Blob对象，用于下载
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'data.csv'; // 下载文件名
        link.click(); // 触发下载
    }



    // 删除数据
    function deleteRow(index: number) {
        const data = { id: tableData.data[index].id }
        axios.post('http://127.0.0.1:5000/deleteCoffee', data).then(() => {
            fetchTableData()
            ElMessage.success('删除成功')
        }).catch(() => {
            ElMessage.error('删除失败')
        })
    }


    // const tableDataDetail = reactive([
    // { field: 'id', name: '编号' },
    // { field: 'name', name: '房产名称' },
    // { field: 'location', name: '位置' },
    // { field: 'house_type', name: '户型' },
    // { field: 'floor', name: '楼层' },
    // { field: 'area', name: '面积' },
    // { field: 'orientation', name: '朝向' },
    // { field: 'total_price', name: '总价' },
    // { field: 'unit_price', name: '每平方价格' },
    // ])
    // 
    // 新增数据
    const CreateDataDetail = reactive({
        data: [
            { value: '', field: 'id', name: '编号' },
            { value: '', field: 'name', name: '房产名称' },
            { value: '', field: 'location', name: '位置' },
            { value: '', field: 'house_type', name: '户型' },
            // { value: '', field: 'floor', name: '楼层' },
            { value: '', field: 'area', name: '面积' },
            { value: '', field: 'orientation', name: '朝向' },
            { value: '', field: 'total_price', name: '总价' },
            { value: '', field: 'unit_price', name: '每平方价格' },
        ]
    })

    const isCreate = ref(false)

    function process() {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        axios.get('http://127.0.0.1:5000/process').then(() => {
            loading.close()
            ElMessage.success('处理成功')
        }).catch(() => {
            loading.close()
            ElMessage.error("处理失败")
        })
    }

    function crawl() {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        axios.post('http://127.0.0.1:5000/spider', CreateDataDetail).then(() => {
            // fetchTableData()
            loading.close()
            ElMessage.success('爬取成功')

        }).catch(() => {
            loading.close()
            ElMessage.error('爬取失败')
        })
    }

    function realyCreate() {
        axios.post('http://127.0.0.1:5000/createCModel', CreateDataDetail).then(() => {
            fetchTableData()
            ElMessage.success('新增成功')
        }).catch(() => {
            ElMessage.error('新增失败')
        })
    }

    // 修改数据
    const isWrite = ref(false)
    const ruleForm = reactive({
        id: null,
        data: [
            { value: '', field: 'id', name: '编号' },
            { value: '', field: 'name', name: '房产名称' },
            { value: '', field: 'location', name: '位置' },
            { value: '', field: 'house_type', name: '户型' },
            // { value: '', field: 'floor', name: '楼层' },
            { value: '', field: 'area', name: '面积' },
            { value: '', field: 'orientation', name: '朝向' },
            { value: '', field: 'total_price', name: '总价' },
            { value: '', field: 'unit_price', name: '每平方价格' },
        ]
    })

    function writeRow(index: number | null) {
        if (index !== null) {
            const item = tableData.data[index]
            // ruleForm.id = item.id
            // console.log("id"+ruleForm.id)
            // ruleForm.data.forEach(field => {
            // field.value = item[field.field]
            // })
            // 假设 item.id 是您要发送的房产ID
            axios.post('http://127.0.0.1:5000/Favorites', { id: item.id })
                .then(() => {
                    // 请求成功后显示消息
                    ElMessage({
                        message: '收藏成功',
                        type: 'success'
                    });
                })
                .catch(() => {
                    // 请求失败后显示消息
                    ElMessage.error('收藏失败');
                });
        }
        // isWrite.value = !isWrite.value
    }

    function realyWrite() {
        axios.post('http://127.0.0.1:5000/updateCoffee', ruleForm).then(() => {
            fetchTableData()
            ElMessage.success('修改成功')
        }).catch(() => {
            ElMessage.error('修改失败')
        })
    }
</script>


<style scoped>
    .demo-pagination-block+.demo-pagination-block {
        margin-top: 10px;
    }

    .demo-pagination-block .demonstration {
        margin-bottom: 16px;
    }

    .action-buttons {
        display: flex;
        align-items: center;
        gap: 10px;
        margin: -5px;
    }

    .writeFrom {
        margin: 0 auto;
        background: #ffffff;
        position: absolute;
        left: 35%;
        top: 35%;
        z-index: 999;
        border: 1px solid #8a8a8a;
        text-align: center;
        line-height: 50px;
        padding: 10px 40px 30px 0;
    }

    .writeForm {
        width: 400px;
        height: 450px;
        /* transform: translate(-50%,-50%); */
        padding: 20px;
        clear: both;
        background: rgb(255, 255, 255);
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        z-index: 999;
        border: 1px solid #ccc;
    }

    li {
        list-style: none;
        padding: 10px;
        display: flex;
        justify-content: space-around;
    }

    p {
        flex: 3;
        text-align: center;
    }

    .elInput {
        flex: 10;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        flex: 10;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #0b0c0c;
        width: 178px;
        height: 178px;
        border: 1px solid #000;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .el-pagination .el-pager li.is-active {
        background-color: #409EFF;
        /* 激活页的背景颜色 */
        color: white;
    }

    /* .img{
		background: #000;
	} */
</style>